{% extends "后台管理/template.html" %}

{% block title %}
系统公告栏
{% endblock %}

{% block css %}
<style>
    .announcement-list {
        list-style: none;
        padding: 0;
        margin: 0;
    }

    .announcement-item {
        padding: 15px;
        border-bottom: 1px solid #ebeef5;
        cursor: pointer;
        transition: background 0.3s ease;
    }

    .announcement-item:hover {
        background: #f9f9f9;
    }

    .announcement-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
    }

    .announcement-meta {
        font-size: 13px;
        color: #999;
    }

    .empty-tip {
        text-align: center;
        padding: 40px 0;
        color: #999;
    }

    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255,255,255,0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 添加公告按钮 -->
    <div class="d-flex justify-content-end mb-3">
        <button class="btn btn-primary" onclick="showAddAnnouncementModal()">
            <i class='bx bx-plus me-1'></i> 添加系统公告
        </button>
    </div>
    <!-- 公告列表 -->
    <ul class="announcement-list" id="announcementList">
        <!-- 公告列表将通过JS动态插入 -->
    </ul>

    <!-- 分页器 -->
    <nav class="d-flex justify-content-center mt-4" id="pagination" style="display: none;">
        <ul class="pagination">
            <!-- 分页按钮将通过JS动态插入 -->
        </ul>
    </nav>

    <!-- 加载中遮罩 -->
    <div class="loading-overlay" id="loadingOverlay" style="display: none;">
        <div class="spinner-border text-primary" role="status">
            <span class="sr-only">加载中...</span>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
let currentPage = 1;
const pageSize = 10;

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    getAnnouncementList();
});

// 获取公告列表
async function getAnnouncementList() {
    try {
        showLoading();
        const response = await fetch(`/api/system/get_system_announcement/?page=${currentPage}&page_size=${pageSize}`);
        const data = await response.json();
        
        if(data.code === 200) {
            renderAnnouncementList(data.data.results);
            renderPagination(data.data.count);
        } else {
            throw new Error(data.message);
        }
    } catch(error) {
        console.error('获取公告列表失败:', error);
        showToast('获取公告列表失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 渲染公告列表
function renderAnnouncementList(announcements) {
    const container = document.getElementById('announcementList');
    
    if(!announcements || announcements.length === 0) {
        container.innerHTML = `
            <div class="empty-tip">
                <i class='bx bx-info-circle fs-3 mb-2'></i>
                <p>暂无公告</p>
            </div>
        `;
        return;
    }
    
    container.innerHTML = announcements.map(announcement => `
        <li class="announcement-item" onclick="showAnnouncementDetail(${announcement.id})">
            <div class="announcement-title">${announcement.title}</div>
            <div class="announcement-meta">
                发布者: ${announcement.username} | 发布时间: ${formatDateTime(announcement.create_time)}
            </div>
        </li>
    `).join('');
}

// 渲染分页器
function renderPagination(total) {
    const totalPages = Math.ceil(total / pageSize);
    const pagination = document.getElementById('pagination');
    const ul = pagination.querySelector('ul');
    
    if(totalPages <= 1) {
        pagination.style.display = 'none';
        return;
    }
    
    pagination.style.display = 'flex';
    let html = `
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="javascript:void(0)" onclick="changePage(${currentPage - 1})">
                <i class='bx bx-chevron-left'></i>
            </a>
        </li>
    `;
    
    for(let i = 1; i <= totalPages; i++) {
        html += `
            <li class="page-item ${currentPage === i ? 'active' : ''}">
                <a class="page-link" href="javascript:void(0)" onclick="changePage(${i})">${i}</a>
            </li>
        `;
    }
    
    html += `
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="javascript:void(0)" onclick="changePage(${currentPage + 1})">
                <i class='bx bx-chevron-right'></i>
            </a>
        </li>
    `;
    
    ul.innerHTML = html;
}

// 切换页码
function changePage(page) {
    currentPage = page;
    getAnnouncementList();
    window.scrollTo(0, 0);
}

// 显示公告详情
async function showAnnouncementDetail(id) {
    try {
        showLoading();
        const response = await fetch(`/api/system/get_system_announcement_detail/?system_announcement_id=${id}`);
        const data = await response.json();
        
        if (data.code === 200) {
            renderAnnouncementDetail(data.data);
        } else {
            throw new Error(data.message);
        }
    } catch (error) {
        console.error('获取公告详情失败:', error);
        showToast('获取公告详情失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 渲染公告详情
function renderAnnouncementDetail(announcement) {
    const modalContent = document.createElement('div');
    modalContent.innerHTML = `
        <h3>${announcement.title}</h3>
        <p>${announcement.content}</p>
        <div class="post-meta">
            <span>发布者: ${announcement.user_id}</span>
            <span>发布时间: ${formatDateTime(announcement.create_time)}</span>
        </div>
    `;
    
    if (announcement.media_data && announcement.media_data.length > 0) {
        const images = announcement.media_data.filter(media => media.media_type === '图片');
        if (images.length > 0) {
            const grid = document.createElement('div');
            grid.className = 'image-grid';
            grid.innerHTML = images.map(img => `
                <div class="image-item">
                    <a href="${img.media_url}" data-lightbox="announcement-images">
                        <img src="${img.media_url}" alt="图片">
                    </a>
                </div>
            `).join('');
            modalContent.appendChild(grid);
        }
    }
    
    const modal = new bootstrap.Modal(document.getElementById('announcementDetailModal'));
    const modalBody = document.getElementById('announcementDetailBody');
    modalBody.innerHTML = '';
    modalBody.appendChild(modalContent);
    modal.show();
}

// 添加公告详情模态框
const modalHtml = `
<div class="modal fade" id="announcementDetailModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">公告详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="announcementDetailBody">
                <!-- 公告详情内容将通过JS动态插入 -->
            </div>
        </div>
    </div>
</div>
`;
document.body.insertAdjacentHTML('beforeend', modalHtml);

// 在页面加载时引入 lightbox 库
const lightboxLink = document.createElement('link');
lightboxLink.rel = 'stylesheet';
lightboxLink.href = 'https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/css/lightbox.min.css';
document.head.appendChild(lightboxLink);

const lightboxScript = document.createElement('script');
lightboxScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/js/lightbox.min.js';
document.body.appendChild(lightboxScript);

// 添加九宫格样式
const gridStyle = document.createElement('style');
gridStyle.innerHTML = `
.image-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
    margin-top: 20px;
}

.image-item img {
    width: 100%;
    height: auto;
    display: block;
    border-radius: 8px;
    transition: transform 0.3s ease;
}

.image-item img:hover {
    transform: scale(1.05);
}
`;
document.head.appendChild(gridStyle);

// 格式化日期时间
function formatDateTime(dateStr) {
    if (!dateStr) return '未知时间'; // 如果日期字符串无效，返回默认值
    const date = new Date(dateStr.replace(/-/g, '/'));
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 显示加载中
function showLoading() {
    document.getElementById('loadingOverlay').style.display = 'flex';
}

// 隐藏加载中
function hideLoading() {
    document.getElementById('loadingOverlay').style.display = 'none';
}

// 添加系统公告
async function addSystemAnnouncement() {
    const userId = document.getElementById('announcementUserId').value.trim();
    const title = document.getElementById('announcementTitle').value.trim();
    const content = document.getElementById('announcementContent').value.trim();
    const isPinned = document.getElementById('announcementIsPinned').checked;
    
    if (!userId || !title || !content) {
        showToast('请填写完整的公告信息', 'error');
        return;
    }
    
    try {
        showLoading();
        const response = await fetch('/api/system/add_system_announcement/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `user_id=${encodeURIComponent(userId)}&title=${encodeURIComponent(title)}&content=${encodeURIComponent(content)}&is_pinned=${isPinned}`
        });
        
        const data = await response.json();
        if (data.code === 200) {
            showToast('公告添加成功', 'success');
            showAddMediaModal(); // 显示添加媒体资源的模态框
            document.getElementById('announcementMedia').dataset.announcementId = data.data.id; // 存储公告ID
        } else {
            throw new Error(data.message);
        }
    } catch (error) {
        console.error('添加公告失败:', error);
        showToast('添加公告失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 添加系统公告媒体资源
async function addAnnouncementMedia() {
    const mediaInput = document.getElementById('announcementMedia');
    const mediaType = document.getElementById('announcementMediaType').value;
    const mediaFiles = mediaInput.files;
    const announcementId = mediaInput.dataset.announcementId; // 获取公告ID
    
    if (!announcementId) {
        showToast('无法获取公告ID，请重试', 'error');
        return;
    }

    if (mediaFiles.length === 0) {
        showToast('请选择要上传的媒体文件', 'error');
        return;
    }
    
    try {
        showLoading();
        for (const file of mediaFiles) {
            const formData = new FormData();
            formData.append('system_announcement_id', announcementId);
            formData.append('media_url', file);
            formData.append('media_type', mediaType);
            
            const response = await fetch('/api/system/add_system_announcement_media/', {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            if (data.code !== 200) {
                throw new Error(data.message);
            }
        }
        showToast('媒体资源添加成功', 'success');
        getAnnouncementList(); // 刷新公告列表
    } catch (error) {
        console.error('添加媒体资源失败:', error);
        showToast('添加媒体资源失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 添加公告模态框
const addAnnouncementModalHtml = `
<div class="modal fade" id="addAnnouncementModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加系统公告</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addAnnouncementForm">
                    <div class="mb-3">
                        <label class="form-label">用户ID</label>
                        <input type="text" class="form-control" id="announcementUserId" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">公告标题</label>
                        <input type="text" class="form-control" id="announcementTitle" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">公告内容</label>
                        <textarea class="form-control" id="announcementContent" rows="3" required></textarea>
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="announcementIsPinned">
                        <label class="form-check-label" for="announcementIsPinned">
                            置顶公告
                        </label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addSystemAnnouncement()">
                    <i class='bx bx-save me-1'></i>保存
                </button>
            </div>
        </div>
    </div>
</div>
`;
document.body.insertAdjacentHTML('beforeend', addAnnouncementModalHtml);

// 添加媒体资源模态框
const addMediaModalHtml = `
<div class="modal fade" id="addMediaModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加媒体资源</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addMediaForm">
                    <div class="mb-3">
                        <label class="form-label">媒体类型</label>
                        <select class="form-select" id="announcementMediaType">
                            <option value="1">图片</option>
                            <option value="2">视频</option>
                            <option value="3">音频</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">选择文件</label>
                        <input type="file" class="form-control" id="announcementMedia" multiple>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addAnnouncementMedia()">
                    <i class='bx bx-upload me-1'></i>上传
                </button>
            </div>
        </div>
    </div>
</div>
`;
document.body.insertAdjacentHTML('beforeend', addMediaModalHtml);

// 显示添加公告模态框
function showAddAnnouncementModal() {
    document.getElementById('addAnnouncementForm').reset();
    const modal = new bootstrap.Modal(document.getElementById('addAnnouncementModal'));
    modal.show();
}

// 显示添加媒体资源模态框
function showAddMediaModal() {
    document.getElementById('addMediaForm').reset();
    const modal = new bootstrap.Modal(document.getElementById('addMediaModal'));
    modal.show();
}
</script>
{% endblock %}

{% block nav_left %}
{% endblock %}

{% block NavBar %}
{% include '后台管理/components/左侧导航栏.html' %}
{% endblock %}

{% block footer %}
{% include '后台管理/components/Footer.html' %}
{% endblock %}